package cn.edu.ctgu.ch1.initial;

import cn.edu.ctgu.ch1.WordsService;
import cn.edu.ctgu.ch1.config.WordConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Scanner;
import java.util.function.IntSupplier;

/**
 * 缺省实现单词服务接口
 *
 * @author tiger54910
 * @create 2025/1/30 16:23
 */
@Service
public class DefaultWordService implements WordsService {

  private static final int MULTIPLY_FACTOR = 100;
  private static final IntSupplier DEFAULT_INDEX_PROVIDER = DefaultWordService::getIndexForToday;
  private final IntSupplier indexProvider;

  private final Path filePath;
  private final WordConfig config;

  @Autowired
  public DefaultWordService(WordConfig config) {
    this(config, DEFAULT_INDEX_PROVIDER);
  }

  public DefaultWordService(WordConfig config,IntSupplier indexProvider) {
    this.config = config;
    this.filePath = getPath(config.getDictionary());
    this.indexProvider = indexProvider;
  }


  @Override
  public String getWordOfTheDay() {
    int index = indexProvider.getAsInt();
    try {
      Scanner scanner = new Scanner(filePath.toFile());
      int i = 0;
      while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (index == i) {
          return line;
        }
        ++i;
      }
    } catch (FileNotFoundException e) {
      throw new RuntimeException("Problem in getWordOfTheDay for index: " + filePath, e);
    }

    return "no word today.";
  }

  @Override
  public boolean wordExists(String word) {
    try {
      Scanner scanner = new Scanner(filePath);
      while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (word.equals(line)) {
          return true;
        }
      }
    } catch (IOException e) {
      throw new RuntimeException("Problem in wordExists for word: " + word, e);
    }
    return false;
  }

  private static int getIndexForToday() {
    LocalDate now = LocalDate.now();
    return now.getYear() + now.getDayOfYear() * MULTIPLY_FACTOR;
  }

  private Path getPath(String file) {
    return Paths.get(new File(file).toURI());
  }
}
